<?php

namespace App\Http\Controllers\Api;
use App\Blocks\CrowdBlock;
use App\Libs\ResponseMessage;
use App\Models\CrowdJoinOrder;
use App\Models\Orders as Order;
use EasyWeChat\Factory;
use Illuminate\Http\Request;
use App\Models\CrowdActivityComment;
use App\Blocks\ActivityBlock;

class WechatController{
    public function weChatPay(Request $request){
        if(!$request->has('order_id')){
            return response()->json(ResponseMessage::getInstance()->failed('PARAM_ERROR')->response());
        }


        $type = $request->get('type', 'order');
        \Log::debug($type);

        $orderId = $request->get('order_id');
        $out_trade_no = date('YmdHis', time()) . mt_rand(0, 1000);
        $config = \Config::get('wechat.payment.default');

        $result = [];
        if($type === 'order') {
            $order = Order::where('id', $orderId)
                ->where('status', 0)
                ->whereNull('pay_time')
                ->first();

            if (!$order) {
                return response()->json(ResponseMessage::getInstance()->failed('PARAM_ERROR')->response());
            }

            $config['notify_url'] = env('APP_URL').'/api/0.0.1/wechat/pay/notify/order';
            $app = Factory::payment($config);

            $result = $app->order->unify([
                'body' => '购买商品',
                'out_trade_no' => $out_trade_no,
//                'total_fee' => $order->pay_total,
                'total_fee' => 1,
                'trade_type' => 'APP',
            ]);

            if (Order::where('id', $orderId)->update([
                    'out_trade_no' => $out_trade_no,
                    'status' => 1
                ]) === false) {
                \Log::error("订单{$orderId}更新out_trade_no失败");
                return response()->json(ResponseMessage::getInstance()->failed()->response());
            }
        }else if($type === 'joincrowd'){
            $order = CrowdJoinOrder::where('id', $orderId)
                ->where('is_pay', 0)
                ->whereNull('pay_time')
                ->first();

            \Log::debug('joincrowd：'.json_encode($order));

            if (!$order) {
                return response()->json(ResponseMessage::getInstance()->failed('PARAM_ERROR')->response());
            }

            $config['notify_url'] = env('APP_URL').'/api/0.0.1/wechat/pay/notify/joincrowd';
            $app = Factory::payment($config);


            $result = $app->order->unify([
                'body' => '加入群',
                'out_trade_no' => $out_trade_no,
                'total_fee' => 1,
                'trade_type' => 'APP',
            ]);

            if (CrowdJoinOrder::where('id', $orderId)->update([
                    'out_trade_no' => $out_trade_no
                ]) === false) {
                \Log::error("订单{$orderId}更新out_trade_no失败");
                return response()->json(ResponseMessage::getInstance()->failed()->response());
            }
        }else if($type == 'activity'){
            $order = CrowdActivityComment::where('id',$orderId)
                ->where('is_pay', 0)
                ->whereNull('pay_time')
                ->first();

            \Log::debug('activity：'.json_encode($order));

            if (!$order) {
                return response()->json(ResponseMessage::getInstance()->failed('PARAM_ERROR')->response());
            }

            $config['notify_url'] = env('APP_URL').'/api/0.0.1/wechat/pay/notify/activity';
            $app = Factory::payment($config);

            $result = $app->order->unify([
                'body' => '参与活动',
                'out_trade_no' => $out_trade_no,
                'total_fee' => 1,
                'trade_type' => 'APP',
            ]);

            \Log::debug($orderId);

            if (CrowdActivityComment::where('id', $orderId)->update([
                    'out_trade_no' => $out_trade_no
                ]) === false) {
                \Log::error("订单{$orderId}更新out_trade_no失败");
                return response()->json(ResponseMessage::getInstance()->failed()->response());
            }
        }

        if(!empty($result)) {
            if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {
                $result = $app->jssdk->appConfig($result['prepay_id']);//第二次签名
                \Log::debug($result);
                return response()->json(ResponseMessage::getInstance()->success($result)->response());
            } else {
                \Log::error('微信支付签名失败:' . var_export($result, 1));
                return response()->json(ResponseMessage::getInstance()->failed()->response());
            }
        }else{
            return response()->json(ResponseMessage::getInstance()->failed()->response());
        }
    }

    public function notify($version, $type){


        \Log::debug($version);
        $app = Factory::payment(\Config::get('wechat.payment.default'));
        $response = $app->handlePaidNotify(function ($message, $fail) use ($type) {
            if($type === 'order') {
                $order = Order::where('out_trade_no', $message['out_trade_no'])
                    ->first();
                if (!$order || $order->status != 0) {
                    return true;
                }
            }else if($type === 'joincrowd'){
                $order = CrowdJoinOrder::where('out_trade_no', $message['out_trade_no'])
                    ->first();
                if (!$order || $order->is_pay != 0) {
                    return true;
                }
            }else if($type === 'activity'){
                $order = CrowdActivityComment::where('out_trade_no', $message['out_trade_no'])
                    ->first();
                if (!$order || $order->is_pay != 0) {
                    return true;
                }
            }else{
                return true;
            }

            if ($message['return_code'] === 'SUCCESS') {

                if (array_get($message, 'result_code') === 'SUCCESS') {

                    if($type === 'order') {
                        if (Order::where('id', $order->id)->update([
                                'pay_time' => date('Y-m-d H:i:s', time()),
                                'status' => 1
                            ]) === false) {
                            \Log::error("更新订单{$type} {$order->id}失败");
                            return $fail('更新订单失败');
                        }
                    }else if($type === 'joincrowd'){
                        $crowdBlock = new CrowdBlock();
                        if ($crowdBlock->joinCrowdToPay($order->id) === false) {
                            \Log::error("更新订单{$type} {$order->id}失败");
                            return $fail('更新订单失败');
                        }
                    }else if($type === 'activity'){
                        $activityBlock = new ActivityBlock();
                        if ($activityBlock->takePayActivity($order)=== false) {
                            \Log::error("更新订单{$type} {$order->id}失败");
                            return $fail('更新订单失败');
                        }
                    }
                }
            } else {
                return $fail('通信失败，请稍后再通知我');
            }
            return true;

        });
        return $response;

    }

}
